<?php

class UserController extends AdminController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	// public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new User;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['User']))
		{
			$model->attributes=$_POST['User'];
			if (!empty($model->password))
				$model->scenario = 'change_password';
				
			if($model->save()) {
				// change password
				if (!empty($model->password)) {
					$model->password_hash = md5($model->password);
					$model->update('password_hash');
				}
				
				// remove images
				if (isset($_POST['remove_images'])) {
					// delete image in remote server
					$imgs = ProfileImage::model()->findAll("id IN (". implode(',', $_POST['remove_images']) .")");
					$paths = array();
					foreach($imgs as $img) {
						$paths[] = $img->file;
					}
					$apiUrl = Yii::app()->params['imageServer'].'deleteMulti';
					$wc = new WebClient();
					$wc->post($apiUrl, array('paths'=>$paths));

					// delete local image
					ProfileImage::model()->deleteAll("id IN (". implode(',', $_POST['remove_images']) .")");
				}
				Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
				$this->redirect(array('update','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Membership number
	 */
	public function actionIndex()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];
		$summary = $model->getSummaryData();
		
		$this->render('number/grid',array(
			'model'=>$model,
			'summ' => $summary,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionSearch()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];
		
		$this->render('search/grid',array(
			'model'=>$model,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionFind()
	{
		$model=new User('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['User']))
			$model->attributes=$_GET['User'];
		
		$this->render('find/grid',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

	public function actionDeleteImage($id)
	{
		$model=ProfileImage::model()->findByPk($id);
		if ($model) {
			$uid = $model->user_id;
			if ($model->delete()) {
				Yii::app()->user->setFlash('success',Yii::t('app', 'Data has been saved'));
			} else {
				Yii::app()->user->setFlash('error',Yii::t('app', 'An error occurred while processing your request'));
			}
		} else {
			throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
		}
		$this->redirect(array('update', 'id'=>$id));	
	}
	
	public function actionTest() {
		$imgs = ProfileImage::model()->findAll();
		$paths = array();
		foreach($imgs as $img) {
			$paths[] = $img->file;
		}
		$apiUrl = Yii::app()->params['imageServer'].'deleteMulti';
		$wc = new WebClient();
		$wc->post($apiUrl, array('paths'=>$paths));
	}
}
